<template>
	<view class="publishDemand">
		<view class="publishDemand-content">
			<view class="formLabel uni-flex uni-align-center uni-justify-between">
				<text>通知与提醒</text>
				<switch color="#2F80ED" />
			</view>
		</view>
		<view class="subtitle">账号与安全中心</view>
		<view class="publishDemand-content">
			<view class="formLabel uni-flex border-bottom uni-justify-between bankCode">
				<text>实名认证</text>
				<view class="uni-flex uni-align-center" @click="showAuthentication">
					<view class="slectBank">{{userInfoData.isRealName === 'YES' ? '已实名' : '未实名'}}</view>
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>
			<view class="formLabel uni-flex border-bottom uni-justify-between bankCode">
				<text>更改手机号</text>
				<view class="uni-flex uni-align-center" @click="showChangeTel">
					<!-- 这里显示的手机号会在onShow中更新 -->
					<view class="slectBank">{{userInfoData.phone ? formatPhone(userInfoData.phone) : '未绑定'}}</view>
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>
			<view class="formLabel uni-flex uni-align-center uni-justify-between border-bottom">
				<text>隐私保护</text>
				<switch checked color="#2F80ED" />
			</view>
			<!-- 	<view class="formLabel uni-flex uni-justify-between bankCode border-bottom">
				<text>用户黑名单</text>
				<view class="uni-flex uni-align-center" @click="showBlackList">
					<view class="slectBank">已开启</view>
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view> -->
			<view class="formLabel uni-flex border-bottom uni-justify-between bankCode">
				<text>修改支付密码</text>
				<view class="uni-flex uni-align-center" @click="goModifyPayPassword">
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>
			<view class="formLabel uni-flex  uni-justify-between bankCode">
				<text>忘记支付密码</text>
				<view class="uni-flex uni-align-center" @click="goForgotToPayPassword">
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>
		</view>
		<view class="subtitle">通用</view>
		<view class="publishDemand-content">
			<view class="formLabel uni-flex border-bottom uni-justify-between bankCode">
				<text>银行卡</text>
				<view class="uni-flex uni-align-center" @click="showBankcard">
					<view class="slectBank">去绑定</view>
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>
			<view class="formLabel uni-flex border-bottom uni-justify-between">
				<text>地址簿</text>
				<view class="uni-flex uni-align-center" @click="showAddress">
					<view class="slectBank">去添加</view>
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>
			<view class="formLabel uni-flex uni-justify-between">
				<text>服务技能</text>
				<view class="uni-flex uni-align-center" @click="showService">
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>
		</view>
		<view class="publishDemand-content" style="margin-top: 32rpx;">
			<view class="formLabel uni-flex uni-justify-between bankCode" @click="clearCache">
				<text>清理缓存</text>
				<view class="uni-flex uni-align-center">
					<view class="slectBank">{{cacheSize}}</view>
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>
			<!-- 小程序不要这个按钮 -->
			<!-- <view class="formLabel uni-flex uni-justify-between">
				<text>当前版本</text>
				<view class="uni-flex uni-align-center">
					<view class="slectBank">V1.0.02</view>
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view> -->
		</view>
		<view class="publishDemand-content" style="margin-top: 32rpx;">
			<view class="formLabel uni-flex uni-align-center uni-justify-between" @click="goDelAccount">
				<text>注销账号</text>
				<view class="uni-flex uni-align-center">
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>
		</view>
		<view class="publishDemand-button" @click="exitLogon">退出登录</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,

	} from "vue";
	import {
		startEid
	} from '@/mp_ecard_sdk/main';
	import {
		getEToken,
		pushEToken,
		userInfo
	} from "@/api/user.js";
	import {
		onShow
	} from '@dcloudio/uni-app'; // 确保导入onShow
	import {
		exitLogin
	} from '@/api/user.js'
	const userInfoData = ref({});
	import {
		setLoggingOut
	} from '@/api/request.js' // 导入设置退出状态的方法
	import store from '@/store/index.js'; // 确保导入store
	const cacheSize = ref('0KB')
	// 手机号脱敏处理（可选，和修改页面保持一致）
	const formatPhone = (phone) => {
		return phone.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1****$3');
	};
	// #ifdef MP-WEIXIN
	// 获取缓存大小的方法
	const getCacheSize = () => {
		wx.getStorageInfo({
			success: (res) => {
				const size = res.currentSize; // 单位KB
				if (size < 1024) {
					cacheSize.value = `${size}KB`;
				} else {
					cacheSize.value = `${(size / 1024).toFixed(2)}MB`;
				}
			},
			fail: (err) => {
				console.error('获取缓存大小失败:', err);
				cacheSize.value = '0KB';
			},
		});
	};

	// 清理缓存的方法
	const clearCache = () => {
		uni.showModal({
			title: '提示',
			content: '确定要清除缓存吗？',
			success: (res) => {
				if (res.confirm) {
					wx.clearStorage({
						success: () => {
							getCacheSize();
							uni.showToast({
								title: '缓存已清除',
								icon: 'success',
								duration: 1500,
							});

							// 检查 access_token 是否存在
							setTimeout(() => {
								const token = uni.getStorageSync('access_token');
								if (!token) {
									store.commit('clearLoginInfo');
									uni.reLaunch({
										url: '/pages/login/index',
										fail: (err) => {
											console.error('跳转失败:', err);
											uni.redirectTo({
												url: '/pages/login/index',
											});
										},
									});
								}
							}, 1500);
						},
						fail: (err) => {
							console.error('清除缓存失败:', err);
							uni.showToast({
								title: '清除失败',
								icon: 'none',
							});
						},
					});
				}
			},
		});
	};
	// #endif
	// 页面首次挂载时读取用户信息
	onMounted(() => {
		loadUserInfo(); // 抽取为通用方法
		// #ifdef MP-WEIXIN
		getCacheSize()
		// #endif
	});

	// 页面显示时（包括从其他页面返回）重新读取用户信息（核心解决逻辑）
	onShow(() => {
		const token = uni.getStorageSync('access_token');
		if (!token) {
			uni.reLaunch({
				url: '/pages/login/index',
			});
		} else {
			loadUserInfo();
		}

	});

	// 抽取读取用户信息的通用方法（包含 token 检查）
	const loadUserInfo = () => {
		const user_info = uni.getStorageSync('user_info');
		const token = uni.getStorageSync('access_token');

		if (!token) {
			uni.reLaunch({
				url: '/pages/login/index',
			});
			return;
		}

		if (user_info) {
			userInfoData.value = JSON.parse(user_info);
		} else {
			userInfo().then((res) => {
				if (res.code === 200) {
					userInfoData.value = res.data;
					uni.setStorageSync('user_info', JSON.stringify(res.data));
				} else {
					uni.reLaunch({
						url: '/pages/login/index',
					});
				}
			}).catch(() => {
				uni.reLaunch({
					url: '/pages/login/index',
				});
			});
		}
	};

	// 以下方法保持不变
	const showAddress = () => {
		uni.navigateTo({
			url: "/pages/tabBars/serviceAddress/serviceAddress"
		});
	};
	const showChangeTel = () => {
		uni.navigateTo({
			url: `/pages/personalCenter/changeTel/index`
		});
	};
	// 用户黑名单
	// const showBlackList = () => {
	// 	uni.navigateTo({
	// 		url: "/pages/personalCenter/blackList/index"
	// 	});
	// };
	const goForgotToPayPassword = () => {
		uni.navigateTo({
			url: "/pages/personalCenter/Universal/ForgotToPayPassword"
		});
	};
	const goModifyPayPassword = () => {
		uni.navigateTo({
			url: "/pages/personalCenter/Universal/ModifyPayPassword"
		});
	};
	const showService = () => {
		uni.navigateTo({
			url: '/pages/contract/addService',
		});
	};
	// 注销账号页面
	const goDelAccount=()=>{
		uni.navigateTo({
			url: '/pages/tabBars/DeleteAccount/DeleteAccountIndex',
		});
	}
	const showAuthentication = () => {
		getEToken().then(res => {
			const {
				eidToken
			} = res.data;
			console.log('获取token成功:', eidToken);
			startEid({
				data: {
					token: eidToken,
					enableEmbedded: true,
					allowFullScreen: false
				},
				verifyDoneCallback(res) {
					const {
						token,
						verifyDone
					} = res;
					console.log('收到核身完成的res:', res);
					pushEToken({
						faceToken: token
					}).then(res => {
						console.log('上传token成功:', res);
						uni.showToast({
							icon: "none",
							title: "实名认证成功"
						});
						userInfo().then((res) => {
							if (res.code == 200) {
								userInfoData.value = res.data;
								uni.setStorageSync('user_info', JSON.stringify(res
									.data));
							} else {
								uni.showToast({
									icon: "none",
									title: res.msg
								});
							}
						});
					});
				},
			});
		});
	};

	// 退出登录方法
	const exitLogon = async () => {
		try {
			const confirm = await uni.showModal({
				title: '确认退出',
				content: '您确定要退出登录吗？'
			});

			if (confirm.confirm) {
				// 设置退出状态
				setLoggingOut(true);

				try {
					// 调用退出接口
					const res = await exitLogin();

					if (res.code === 200) {
						// 清理存储
						await Promise.all([
							uni.removeStorageSync('access_token'),
							uni.removeStorageSync('token_expire_time'),
							uni.removeStorageSync('user_info')
						]);

						// 清理vuex/pinia状态
						store.commit('clearLoginInfo');

						// 显示成功提示
						uni.showToast({
							title: '退出成功',
							icon: 'success',
							duration: 1500
						});

						// 延迟跳转确保提示显示
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/login/index',
								fail: (err) => {
									console.error('跳转失败:', err);
									// 备用跳转方式
									uni.redirectTo({
										url: '/pages/login/index'
									});
								}
							});
						}, 1500);
					} else {
						throw new Error(res.msg || '退出失败');
					}
				} catch (error) {
					console.error('退出接口调用失败:', error);

					// 即使接口失败也尝试清理本地数据并跳转
					await Promise.all([
						uni.removeStorageSync('access_token'),
						uni.removeStorageSync('token_expire_time'),
						uni.removeStorageSync('user_info')
					]);
					store.commit('clearLoginInfo');

					uni.showToast({
						title: '退出成功',
						icon: 'success',
						duration: 1000
					});

					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/index'
						});
					}, 1000);
				}
			}
		} catch (error) {
			console.error('退出过程中发生错误:', error);
			uni.showToast({
				title: '操作失败，请重试',
				icon: 'none'
			});
		} finally {
			// 确保最终会重置状态
			setTimeout(() => {
				setLoggingOut(false);
			}, 2000);
		}
	};
	const showBankcard = () => {
		uni.navigateTo({
			url: "/pages/personalCenter/Universal/BankCard"
		});
	};
</script>

<style scoped lang="scss">
	.publishDemand {
		padding: 26rpx 24rpx 81rpx;
		background: #f5f5f5;
		min-height: calc(100vh - 26rpx);

		.subtitle {
			font-weight: 400;
			font-size: 24rpx;
			color: #666666;
			margin: 32rpx 0 24rpx;
		}

		.publishDemand-content {
			background: #ffffff;
			border-radius: 20rpx;
			padding: 0 26rpx 0 23rpx;

			.border-bottom {
				border-bottom: 1px solid #e2e2e2;
			}

			.formLabel {
				padding: 24rpx 0;

				.slectBank {
					font-weight: 400;
					font-size: 28rpx;
					color: #999999;
				}

				text {
					font-weight: 500;
					font-size: 28rpx;
					color: #303133;
					line-height: 70rpx;
				}
			}
		}

		.publishDemand-button {
			width: 100%;
			height: 88rpx;
			background: #ffffff;
			border-radius: 20rpx;
			text-align: center;
			font-weight: 400;
			font-size: 28rpx;
			color: #eb4747;
			line-height: 88rpx;
			margin: 40rpx auto 0;
		}
	}
</style>